//client
//
//Ky Halverson

#include"masterSocket.cpp"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>

#define PORT 9000
#define IP "127.0.0.1"
#define TYPE "TCP"


using namespace std;

string extractData (string message);

int main()
{
	masterSocket* clientSocket;
	clientSocket = new masterSocket(IP, PORT, TYPE);

	string message;
	string messageBack;
	string fileData;
	string frontCheck;
	string newFile;
	
	int header;
	int i = 1;

	ofstream myFile("TRANSFERED_FILE.html");

 
 while(true)
 {

			std::cout<<"\nWhat file do you want from the server(GET /\"whatyoutype\" HTTP/1.1? or type 'EXIT' to kill server and client."<<std::endl;
			getline(cin,message);
			std::cout<<"Requested: GET /"<<message<<" HTTP/1.1"<<std::endl;
			clientSocket->sendIt("CLIENT","GET /"+message+" HTTP/1.1\r\n");
			if (message == "EXIT")
			{
				exit(EXIT_SUCCESS);
			}
			messageBack = clientSocket->recvIt("CLIENT");

			std::cout<<"\nSERVER: "<<messageBack<<std::endl;
			
			header = messageBack.find_first_of("HTTP/1.1");
			frontCheck = messageBack.substr(header,header+12);


			if(frontCheck == "HTTP/1.1 400"||frontCheck == "HTTP/1.1 404")
			{
				std::cout<<"Either bad connection or bad request of file (try again)"<<std::endl;
			}
				
			else			
			{

				fileData = extractData(messageBack);			

				myFile.write(fileData.c_str(),strlen(fileData.c_str()));
				myFile.close();
				
				std::cout<<" File created for you! Good Bye!"<<std::endl;
				break;
				
				clientSocket->sendIt("CLIENT","GET /EXIT HTTP/1.1\r\n");
			}
			fileData = "";							
			messageBack = "";
 }	

return 0; 
}

string extractData (string message)
{
	string file = message;
	int head = file.find_first_of("\n");
	file = file.substr(head+3,message.length());
	
	return file;
	
}
